//
//  StatusDetaiViewController.m
//  xWeibo
//
//  Created by alvis mac on 11/7/15.
//  Copyright © 2015 alvis. All rights reserved.
//
#define kDockHeight 44

#import "StatusDetaiViewController.h"
#import "MJRefresh.h"
#import "StatusDetailTopView.h"
#import "AyStatusFrame.h"
#import "AyDefine.h"
#import "StatusDetailDock.h"
#import "StatusDetailReweetOptionBar.h"
#import "AyStatusCell.h"
#import "AyStatusTool.h"
#import "AyStatusesDetailParame.h"
#import "AyAccountTool.h"
#import "BaseTextFrame.h"
#import "BaseTextModel.h"
#import "NoDataCell.h"
#import "BaseFrame.h"
#import "BaseTextCell.h"

@interface StatusDetaiViewController()<MJRefreshBaseViewDelegate>
{
    UITableView *_tableView; // 表格
    StatusDetailTopView *_topView; // 评论\赞\转发
    
    AyStatusFrame *_detailFrame;  // 第1个cell的frame
    
    NSMutableArray *_repostFrames; // 所有的转发
    BOOL _repostLastPage;
    
    NSMutableArray *_commentFrames; // 所有的评论
    BOOL _commentLastPage;
    
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;

}
@end


@implementation StatusDetaiViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 2.添加子控件
    [self addChildViews];
    
    // 3.加载微博数据
    [self loadStatus];
    
    // 4.加载数据
    [self showData];
}



- (void)addChildViews
{
    self.title = @"微博正文";

    // 1.表格
    CGSize viewSize = self.view.frame.size;
    _tableView = [[UITableView alloc] init];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.frame = CGRectMake(0, 0, viewSize.width, viewSize.height - kDockHeight);
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _tableView.backgroundColor = kGlobalBg;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 10)];
    [self.view addSubview:_tableView];

    // 2.顶部:评论\转发\赞
    
    _topView = [[StatusDetailTopView alloc] init];
    __weak StatusDetaiViewController *detail = self;
    _topView.topViewBtnClick = ^(TopViewBtnType type, TopViewBtnType lastType){
//                if (type == lastType) {
//                    // 滚动第1组第0行
//                    NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:1];
//                    [detail->_tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
//                }
        [detail showData];
    };
    
    // 3.dock
    StatusDetailDock *dock = [[StatusDetailDock alloc] init];
    dock.frame = CGRectMake(0, viewSize.height - kDockHeight, viewSize.width, kDockHeight);
    [self.view addSubview:dock];
    
    // 4.刷新控件
    _header = [[MJRefreshHeaderView alloc] init];
    _header.scrollView = _tableView;
    _header.delegate = self;
    
    _footer = [[MJRefreshFooterView alloc] init];
    _footer.scrollView = _tableView;
    _footer.delegate = self;
    _footer.hidden = YES;
    
    // 5.初始化数据
    _detailFrame = [[AyStatusFrame alloc] init];
    _detailFrame.status = _status;
}



- (void)showData
{
    if (_topView.type == TopViewBtnTypeComment) { // 评论
        [self loadComments];
    } else if (_topView.type == TopViewBtnTypeRepost) { // 转发
        [self loadReposts];
    }
    
    // 刷新表格
    [_tableView reloadData];
}



- (void)loadStatus
{
  [_tableView reloadData];
  [_header endRefreshing];
    // the api power not enough
    /*
    AyStatusesDetailParame * param=[AyStatusesDetailParame param];
    param.access_token=[AyAccountTool account].access_token;
    param.wid=_status.idstr;
    
    [AyStatusTool getStatusDetailWithParam:param success:^(AyStatus *result) {
        // 3.1.更新微博数据
        //[_status updateWithStatus:status];
        
        // 3.2.刷新表格
        [_tableView reloadData];
        
        [_header endRefreshing];
    } failure:^(NSError *error) {
         [_header endRefreshing];
    }];*/
}


- (NSMutableArray *)framesWithContent:(NSMutableArray *)content
{
    NSMutableArray *newFrames = [NSMutableArray array];
    for (BaseTextModel *c in content) {
        BaseTextFrame *f = [[BaseTextFrame alloc] init];
        f.textModel = c;
        [newFrames addObject:f];
    }
    return newFrames;
}

- (void)loadComments
{
    AyStatusCommentParame * param=[AyStatusCommentParame param];
    param.sinceId= @([[self sinceIdInFrames:_commentFrames] intValue]);
    param.id=_status.idstr;
    [AyStatusTool statusCommentWithParam:param success:^(AyStatusCommentResult *result) {
                // 计算新数据的frame
                NSMutableArray *newFrames = [self framesWithContent:result.comments];
        
                // 没有数据就创建
                if (!_commentFrames) {
                    _commentFrames = [NSMutableArray array];
                }
                [newFrames addObjectsFromArray:_commentFrames];
                _commentFrames = newFrames;
                _commentLastPage = _commentLastPage || [@"0" isEqualToString:result.next];
        
                // 更新评论数
                _status.comments_count = result.totalCount;
                
                // 刷新表格
                [_tableView reloadData];
        
    } failure:^(NSError *error) {
    }];
    
}


- (void)loadReposts
{
    AyStatusCommentParame * param=[AyStatusCommentParame param];
    param.sinceId= @([[self sinceIdInFrames:_repostFrames] intValue]);
    param.id=_status.idstr;
    [AyStatusTool statusRepostsWithParam:param success:^(AyRepostsResult *result) {
                // 计算新数据的frame
                NSMutableArray *newFrames = [self framesWithContent:result.reposts];
        
                // 没有数据就创建
                if (!_repostFrames) {
                    _repostFrames = [NSMutableArray array];
                }
                [newFrames addObjectsFromArray:_repostFrames];
                _repostFrames = newFrames;
                _repostLastPage = _repostLastPage || [@"0" isEqualToString:result.next];;
        
                // 更新评论数
                _status.reposts_count = result.totalCount;
                
                // 刷新表格
                [_tableView reloadData];
        
    } failure:^(NSError *error) {
    }];
    
    
}

- (NSString *)sinceIdInFrames:(NSMutableArray *)frames
{
    NSString *sinceId = nil;
    if (frames.count > 0) {
        BaseTextFrame *f =  frames[0];
        sinceId = f.textModel.idstr;
    }
    return sinceId;
}

- (NSString *)maxIdInFrames:(NSMutableArray *)frames
{
    NSString *maxId = nil;
    if (frames.count > 0) {
        BaseTextFrame *f =  [frames lastObject];
        long long maxIdll = [f.textModel.idstr longLongValue] - 1;
        maxId = [NSString stringWithFormat:@"%lld", maxIdll];
    }
    return maxId;
}

#pragma mark 刷新代理
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (_header == refreshView) { // 下拉刷新
        [self loadStatus];
        //[self showData];
    } else {
        if (_topView.type == TopViewBtnTypeComment) {
            [self loadMoreComments];
        } else if (_topView.type == TopViewBtnTypeRepost) {
            [self loadMoreReposts];
        }
    }
}


- (void)loadMoreComments
{
    AyStatusCommentParame * param=[AyStatusCommentParame param];
    param.maxId= @([[self maxIdInFrames:_commentFrames] intValue]);
    param.id=_status.idstr;
    [AyStatusTool statusCommentWithParam:param success:^(AyStatusCommentResult *result) {
                // 计算新数据的frame
                NSMutableArray *newFrames = [self framesWithContent:result.comments];
                [_commentFrames addObjectsFromArray:newFrames];
        
                // 更新评论数
                _status.comments_count = result.totalCount;
                _commentLastPage = [@"0" isEqualToString:result.next];
        
                if (_topView.type == TopViewBtnTypeComment) {
                    [_footer endRefreshing];
                }
                
                // 刷新表格
                [_tableView reloadData];
        
    } failure:^(NSError *error) {
                if (_topView.type == TopViewBtnTypeComment) {
                    [_footer endRefreshing];
                }
    }];
}


- (void)loadMoreReposts
{
    
    AyStatusCommentParame * param=[AyStatusCommentParame param];
    param.maxId= @([[self maxIdInFrames:_repostFrames] intValue]);
    param.id=_status.idstr;
    [AyStatusTool statusRepostsWithParam:param success:^(AyRepostsResult *result) {
        // 计算新数据的frame
        NSMutableArray *newFrames = [self framesWithContent:result.reposts];
        [_repostFrames addObjectsFromArray:newFrames];
        
        // 更新评论数
        _status.reposts_count = result.totalCount;
        _repostLastPage = [@"0" isEqualToString:result.next];
        
        if (_topView.type == TopViewBtnTypeRepost) {
            [_footer endRefreshing];
        }
        
        // 刷新表格
        [_tableView reloadData];
        
    } failure:^(NSError *error) {
        if (_topView.type == TopViewBtnTypeRepost) {
            [_footer endRefreshing];
        }
    }];
    
}



-(void)dealloc{
    [_header free];
    [_footer free];
}


- (NSMutableArray *)getCurrentData
{
    switch (_topView.type) {
        case TopViewBtnTypeComment:
            return _commentFrames;
        case TopViewBtnTypeRepost:
            return _repostFrames;
        case TopViewBtnTypeFavorite:
#warning 待写
            return nil;
    }
    return nil;
}



#pragma mark tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // 每次刷新都检测需不需要隐藏上拉加载更多
    if (_topView.type == TopViewBtnTypeComment) {
        _footer.hidden = _commentLastPage;
    } else if (_topView.type == TopViewBtnTypeRepost) {
        _footer.hidden = _repostLastPage;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 第0组 或者 没有数据，都是显示一行
    if (section == 0 || [self getCurrentData].count == 0) {
        return 1;
    }
    return [self getCurrentData].count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) { // 第1组
        return [self sectionOneCell:indexPath];
    } else if ([self getCurrentData].count == 0) { // 没有数据
        return [self sectionTwoNoDataCell:indexPath];
    } else { // 有数据
        return [self sectionTwoDataCell:indexPath];
    }
}


- (UITableViewCell *)sectionOneCell:(NSIndexPath *)indexPath
{
    AyStatusCell *cell=[AyStatusCell cellWithTableViewWithoutToolBar:_tableView];
    cell.statusFrame = _detailFrame;
    return cell;
}


- (UITableViewCell *)sectionTwoNoDataCell:(NSIndexPath *)indexPath
{
    NoDataCell *cell = [NoDataCell noDataCellWithUITableView:_tableView];
    
    // 是否要显示正在加载
    cell.loading = [self getCurrentData] == nil;
    
    // 更换图片和文字
    if (_topView.type == TopViewBtnTypeFavorite) {
        cell.imageName = @"statusdetail_icon_empty_like.png";
        cell.text = @"还没有人赞";
    } else if (_topView.type == TopViewBtnTypeComment) {
        cell.imageName = @"statusdetail_icon_empty_comment.png";
        cell.text = @"还没有人评论";
    } else {
        cell.imageName = @"statusdetail_icon_empty_retweet.png";
        cell.text = @"还没有人转发";
    }
    
    return cell;
}

- (UITableViewCell *)sectionTwoDataCell:(NSIndexPath *)indexPath
{
    // 评论\转发
    if (_topView.type != TopViewBtnTypeFavorite) {
        return [self textCell:indexPath];
    }
    return nil;
}

- (UITableViewCell *)textCell:(NSIndexPath *)indexPath
{
    BaseTextCell *cell = [BaseTextCell baseTextCellWithUITableView:_tableView];
    if (_topView.type == TopViewBtnTypeComment) {
        cell.baseTextFrame = _commentFrames[indexPath.row];
    } else {
        cell.baseTextFrame = _repostFrames[indexPath.row];
    }
    cell.indexPath = indexPath;
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return (section == 0) ? 0 : _topView.frame.size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) { // 第1组
        return _detailFrame.cellHeight-_detailFrame.statusToolbarF.size.height;
     
    }  else if ([self getCurrentData].count == 0) { // 没有数据
        return 406;
    } else {
        BaseFrame *frame = [self getCurrentData][indexPath.row];
        return frame.cellHeight;
    }
}


#pragma mark 每一组的头部view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    // 更新组头的数据
    _topView.status = _status;
    return (section == 0) ? nil : _topView;
}


@end
